<template>
	<view class="ble_container">
		<button @click="searchBle">搜索蓝牙</button>
		<view class="ble_list" v-if="devices.length">
			<button 
				v-for="(item,index) in devices"
				:key="index" 
				style="width: 100%; color: #fff;" 
				@click="onConn(item)"
			>{{ item.name }}<text v-if="item.name">-</text>{{ item.deviceId }}</button>
		</view>
		<button style="margin-top: 50upx;" @click="stopFindBule">停止搜索</button>
		<!-- <button style="margin-top: 100upx;" @click="senBleLabel()">标签打印</button> -->
		<button style="margin-top: 100upx;" @click="printData">标签打印</button>
		<view class="history" v-if="historyConn.name">
			<view class="title">最近连接设备</view>
			<text class="item" @click="onConn(historyConn)">{{ historyConn.name }}</text>
			<!-- <text class="item">printer</text> -->
		</view>
		<!-- <textarea 
			@blur="bindTextAreaBlur" 
			auto-height 
			placeholder-style="color:#F76260" 
			placeholder="请输入票据信息" 
			v-model="piaojuText" 
		/> -->
		<!-- <button style="margin-top: 100upx;" @click="senBleLabel2()">票据打印</button> -->
	</view>
</template>

<script>
	var tsc = require('../../annex/gprint/tsc.js')
	var esc = require('../../annex/gprint/esc.js')
	export default {
		data() {
			return {
				devices: [],
				currDev: null,
				connId: '',
				piaojuText:'票据打印测试数据',
				canvasWidth: 80,
				canvasHeight: 80,
				storeId: '',
				productId:'',
				printNum: '',
				historyConn: {},
				name: '',
				address: ''
			}
		},
		onLoad(opt) {
			console.log(opt)
			this.printNum = opt.printNum
			this.storeId = opt.store_id
			this.productId = opt.product_id
			this.address = opt.plcae_address
			this.name = opt.name
			this.searchBle()
		},
		onShow() {
			if(uni.getStorageSync('ble')) {
				uni.showLoading({
					title: '连接设备中'
				})
				
				this.historyConn = uni.getStorageSync('ble')
				this.onConn(uni.getStorageSync('ble'))
			}
		},
		onHide() {
			
		},
		onUnload() {
			// uni.closeBLEConnection({
			//    deviceId: this.connId,
			//    success(res) {
			// 	   uni.showToast({
			// 	   	title: res,
			// 	   	duration: '5000'
			// 	   })
			//    },
			//    fail(res) {
			// 	   uni.showToast({
			// 	   	title: res,
			// 	   	duration: '5000'
			// 	   })
			//    }
			// })
			uni.closeBluetoothAdapter({
			   success(res){
			   },
			   fail(res){
			   }
			})
		},
		methods: {
			destroyed: function() {
				console.log("destroyed----------")
				if (this.connId != '') {
					uni.closeBLEConnection({
						deviceId: this.connId,
						success(res) {
							console.log(res)
						}
					})
				}
			},
			bindTextAreaBlur() {},
			// 初始化蓝牙模块
			searchBle() {
				var that = this
				console.log("initBule")
				uni.openBluetoothAdapter({
					success(res) {
						console.log("打开 蓝牙模块")
						console.log(res)
						that.onDevice()
						// that.getDevices()
						uni.getBluetoothAdapterState({
							success: function(res) {
								console.log(res)
								if (res.available) {
									if (res.discovering) {
										that.stopFindBule()
									}
									//搜索蓝牙
									//开始搜寻附近的蓝牙外围设备
									console.log("开始搜寻附近的蓝牙外围设备")
									uni.startBluetoothDevicesDiscovery({
										success(res) {
											console.log(res)
										}
									})

								} else {
									uni.showToast({
										title: '本机蓝牙不可用',
										icon: 'none'
									})
								}
							},
						})
					},
					fail(err) {
						console.log(err.code)
						if(err.code == 10001) {
							uni.showToast({
								title: '当前蓝牙适配器不可用,请检查蓝牙是否开启',
								icon: 'none'
							})
						}
					}
				})
			},
			// 监听寻找到新设备的事件
			onDevice(){
				console.log("监听寻找到新设备的事件---------------")
				var that = this
				//监听寻找到新设备的事件
				uni.onBluetoothDeviceFound(function(devices) {
					// console.log('--new--'+JSON.stringify(devices))
					var re = JSON.parse(JSON.stringify(devices))
					console.log(re)
					// console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
					let name = re.devices[0].name
					if (name != '未知设备') {
						let deviceId = re.devices[0].deviceId
						that.devices.push({
							name: name || '未命名设备',
							deviceId: deviceId,
							services: []
						})
					}
					
				})
			},
			// 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			// getDevices() {
			// 	uni.getBluetoothDevices({
			// 	  success(res) {
			// 	    console.log(res)
			// 	    if (res.devices[0]) {
			// 			// console.log(ab2hex(res.devices[0].advertisData))
			// 			let name = res.devices[0].name
			// 			if (name != '未知设备') {
			// 				let deviceId = res.devices[0].deviceId
			// 				that.devices.push({
			// 					name: name || '未命名设备',
			// 					deviceId: deviceId,
			// 					services: []
			// 				})
			// 			}
			// 	    }
			// 	  }
			// 	})
			// },
			// 停止搜寻附近的蓝牙外围设备
			stopFindBule() {
				console.log("停止搜寻附近的蓝牙外围设备---------------")
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
					}
				})
			},
			// 连接蓝牙
			onConn(item) {
				var that = this
				console.log("连接蓝牙---------------" + item.deviceId)
				let deviceId = item.deviceId
				uni.createBLEConnection({
					deviceId: deviceId,
					complete(res) {
						if (res.errMsg == "createBLEConnection:ok") {
							// console.log("连接蓝牙-[" + item.name + "]--成功")
							uni.showToast({
								title: "连接蓝牙-[" + item.name + "]--成功",
								icon: 'none'
							})
							that.connId = deviceId;
							that.currDev = item
							uni.setStorageSync('ble', item)
							setTimeout(function() {
								that.getBLEServices(deviceId)
							}, 1000)
						} else {
							uni.showToast({
								title: "连接蓝牙-[" + item.name + "]--失败",
								icon: 'none'
							})
							console.log(res)
							uni.hideLoading()
						}
						
						//连接成功 关闭搜索
						that.stopFindBule()

					},
				})
			},
			// 获取蓝牙设备所有服务
			getBLEServices(_deviceId) {
				var that = this;
				let deviceId = _deviceId
				console.log("获取蓝牙设备所有服务(service)。---------------")

				uni.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: deviceId,
					complete(res) {
						console.log(res)
						let serviceId = ""

						for (var s = 0; s < res.services.length; s++) {
							console.log(res.services[s].uuid)
							let serviceId = res.services[s].uuid
							uni.getBLEDeviceCharacteristics({
								// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
								deviceId: deviceId,
								// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
								serviceId: serviceId,
								success(res) {
									var re = JSON.parse(JSON.stringify(res))

									console.log('deviceId = [' + deviceId + ']  serviceId = [' + serviceId + ']')
									for (var c = 0; c < re.characteristics.length; c++) {
										if (re.characteristics[c].properties.write == true) {
											let uuid = re.characteristics[c].uuid
											console.log(' deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +
												uuid)

											for (var index in that.devices) {
												if (that.devices[index].deviceId == deviceId) {
													that.devices[index].services.push({
														serviceId: serviceId,
														characteristicId: uuid
													})
													break
												}
												if(that.historyConn.deviceId == deviceId) {
													that.historyConn.services.push({
														serviceId: serviceId,
														characteristicId: uuid
													})
													break
												}
											}
											console.log(JSON.stringify(that.devices))

										}
									}
								}
							})

						}



					},
					fail(res) {
						console.log(res)
					},
				})

			},
			
			senBlData(deviceId, serviceId, characteristicId,uint8Array) {
				console.log('deviceId = [' + deviceId + '] serviceId = [' + serviceId + '] characteristics=[' +characteristicId+ "]")
				var uint8Buf = Array.from(uint8Array);
				function split_array(datas,size){
					var result = {};
					var j = 0
					for (var i = 0; i < datas.length; i += size) {
						result[j] = datas.slice(i, i + size)
						j++
					}
					console.log(result)
					return result
				}
				var sendloop = split_array(uint8Buf, 20);
				// console.log(sendloop.length)
				function realWriteData(sendloop, i) {
					var data = sendloop[i]
					if(typeof(data) == "undefined"){
						return
					}
					console.log("第【" + i + "】次写数据"+data)
					var buffer = new ArrayBuffer(data.length)
					var dataView = new DataView(buffer)
					for (var j = 0; j < data.length; j++) {
						dataView.setUint8(j, data[j]);
					}
					uni.writeBLECharacteristicValue({
						deviceId,
						serviceId,
						characteristicId,
						value: buffer,
						success(res) {
							realWriteData(sendloop, i + 1);
						},
						fail(err) {
							uni.showToast({
								title: 'errCode' + err.errCode,
								icon: 'none'
							})
						}
					})
				}
               var i = 0;
				realWriteData(sendloop, i);
			},
			printData() {
				this.senBleLabel1()
			},
			// 标签打印
			senBleLabel1() {
				//标签模式
					let deviceId = this.currDev.deviceId;
					let serviceId = this.historyConn.services ? this.historyConn.services[0].serviceId : this.currDev.services[0].serviceId;
					let characteristicId = this.historyConn.services ? this.historyConn.services[0].characteristicId : this.currDev.services[0].characteristicId;
					let str = this.productId
					let name = this.name
					let address = '产地: ' + this.address
					var command = tsc.jpPrinter.createNew()
					// console.log(command)
					for(var i=0; i<this.printNum; i++) {
						command.setSize(40, 30)
						command.setGap(2)
						command.setCls()
						// command.setReference(0,0)
						// command.setFeed(3)
						command.setText(0, 10, "TSS24.BF2", 1, 1, name)
						command.setQR(0, 50, "L", 6, "A", str)
						command.setText(0, 190, "TSS24.BF2", 1, 1, address)
						// command.setText(150, 90, "TSS24.BF2", 1, 1, address)
						command.setPagePrint()
					}
					this.senBlData(deviceId, serviceId, characteristicId,command.getData())
				
			},
			// 票据打印
			senBleLabel2(){
				//票据模式
				let deviceId = this.currDev.deviceId;
				let serviceId = this.currDev.services[0].serviceId;
				let characteristicId = this.currDev.services[0].characteristicId;
				var command = esc.jpPrinter.createNew()
				command.init()
                command.setText(this.piaojuText);
                command.setPrintAndFeedRow(1)
				this.senBlData(deviceId, serviceId, characteristicId,command.getData())
			}
		}
	}
</script>

<style lang="scss">
	.ble_container {
		width: 100%;
		padding: 30rpx;
	}
	.ble_list {
		width: 100%;
		padding: 30rpx;
		background-color: #fff;
		margin-top: 30rpx;
		button {
			&:not(:last-child) {
				margin-bottom: 20rpx;
			}
		}
	}
	button {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #a9d54f;
		color: #fff;
		border-radius: 40rpx;
	}
	.history {
		width: 100%;
		background-color: #fff;
		margin-top: 30rpx;
		padding: 30rpx;
		font-size: 30rpx;
		.title {
			border-bottom: 1px solid #eee;
			padding-bottom: 30rpx;
			margin-bottom: 30rpx;
		}
		.item {
			padding: 10rpx 20rpx;
			background-color: #a9d54f;
			color: #fff;
			border-radius: 10rpx;
		}
	}
</style>
